
Uec3.ShowPurchaseDetailsWindowCreator = Ext.extend(Ext.app.Module, {
   id: 'showPurchaseDetailsWindowCreator',
   type: 'common/notepad',
   iarea: null,

   /**
    * Initialize this module.
    * This function is called at startup (page load/refresh).
    */
   init : function(initParams){
   		
   },
	/**
	 * 打开行记录
	 */
	toUpdatePur : function(id) {
		var record = this.show_details_store.getById(id);
		var desktop = Uec3.App.getDesktop();
		if(record.data.workFlowId + '' == '2') {
			desktop.launchWindowByParam("addAutoPurchaseOrderWindowCreator", {id : record.data.ordersId, 
//														init_status : record.data.status,
														init_buyerCode : record.data.codeOfBuyer
														});
		} else if(record.data.workFlowId + '' == '1') {
			desktop.launchWindowByParam("addOutPurchaseOrderWindowCreator", {id : record.data.ordersId, 
//														init_status : record.data.status,
														init_buyerCode : record.data.codeOfBuyer
														});
		}
	},
		
	/**
	 * Create this modules window here.
	 */
   createWindow : function(){
      var desktop = this.app.getDesktop();
      var win = desktop.getWindow('showDetails');
      if(win) {
		 win.toFront();
      } else {
      	
      	 var versionCode = ++(PurchaseCount.count);
      	 var viewPanel = this.getPanel();
      	
         win = desktop.createWindow({
            id: 'showDetails',
            title: '浏览采购订单明细',
            width: 1010,
            height: 500,
            iconCls: 'acc-icon',
            animCollapse:true,
            constrainHeader: true,
            maximizable: true,
            taskbuttonTooltip: "浏览采购订单明细",
            layout: "fit",
//            tools: [
//               {
//                  id: 'refresh',
//                  handler: Ext.emptyFn,
//                  scope: this
//               }
//             ],
             items:[ viewPanel ]
         });
		 viewPanel.main_win = win;
		 win.versionCode = versionCode;
      	 win.show();
      }
   },
   getPanel : function() {
			
		// 来源下拉框
		var sourceType_store = getDictionaryStore(RES_PATH, {
			group : 'part_source'
		});
		var source_cmb = getDictionaryComboBox(sourceType_store, 'local', 'part_source',
				'来源', 'source');
		sourceType_store.load();
		
		var show_details_record = Ext.data.Record.create( [ 
	       		{
	       			name : 'id'
	       		},{
	       			name : 'code'
	       		}, {
	       			name : 'name'
	       		}, {
	       			name : 'source'
	       		}, {
	       			name : 'measurementUnit'
	       		}, {
	       			name : 'brand'
	       		}, {
	       			name : 'origin'
	       		}, {
	       			name : 'price'
	       		}, {
	       			name : 'codeOfBuyer'
	       		}, {
	       			name : 'orderQuantity'
	       		}, {
	       			name : 'level1Id'
	       		}, {
	       			name : 'partId'
	       		}, {
	       			name : 'level1Name'
	       		}, {
	       			name : 'level2Name'
	       		}, {
	       			name : 'ordersId'
	       		},{
	       			name : 'status'
	       		}, {
	       			name : 'sellerId'
	       		}, {
	       			name : 'workFlowId'
	       		} 
	    ] );
		
	    var show_details_store = new Ext.data.Store( {
			proxy : new Ext.data.HttpProxy(
				{
					url : RES_PATH + '/purchase/getPurDetailsInfoByComplex.do',
					method : 'post'
				}
			),
			pruneModifiedRecords : true, 
			paramNames : {
				start : "start",
				limit : "limit"
	//			sort : "sort",
	//			dir : "dir"   
			},
			remoteSort:true,
			reader : new Ext.data.JsonReader(
				{
					totalProperty : 'totalProperty',
					root : 'root'
				}, 
				show_details_record
			)
					
		} );
		
		this.show_details_store = show_details_store;
	    
	//	var show_details_store = new Ext.data.JsonStore( {
	//		url : PUR_DETAILS_QUERY_URL,
	////		baseParams : {
	////			orderId : this.orderId
	////		},
	//		mode : "local",
	//		totalProperty : "results",
	//		root : "purchaseDetails",
	//		idProperty : "id",
	//		pruneModifiedRecords : true,
	//		fields : show_details_record
	//	} );
		
		var show_details_colName = new Ext.grid.ColumnModel( [ new Ext.grid.RowNumberer(),
			{
				header : '操    作',
				dataIndex : 'id',
				renderer : this.moduleActionRenderer({
					func : "toUpdatePur",
					desc : "查看单据"
				})
			}, {
				header : '单据号',
				dataIndex : 'codeOfBuyer'
			}, {
				header : '零件编码',
				dataIndex : 'code'
			}, {
				header : '零件名称',
				dataIndex : 'name'
			}, {
				header : '来源',
				dataIndex : 'source',
				renderer : Ext.util.Format.comboRenderer(source_cmb)
//				editor : source_cmb
			}, {
				header : '单位',
				dataIndex : 'measurementUnit'
			}, {
				header : '订购数量',
				dataIndex : 'orderQuantity'
			}, {
				header : '订购价',
				dataIndex : 'price'
			}, {
				header : '品牌',
				dataIndex : 'brand',
				sortable : true
			}, {
				header : '产地',
				dataIndex : 'origin',
				sortable : true
			}
		] );
		
		var show_details_grid = new Ext.grid.GridPanel( {
			title : '采购订单明细',
//			id : SHOW_DETAILS_GRID_ID,
			cm : show_details_colName,
			store : show_details_store,
			iconCls : 'icon-grid',
			loadMask : {
				msg : '数据加载中...'
			},
			viewConfig : {
//				forceFit:true
			},
//			width : '100%',
			height : 380,
	//		autoHeight : true,
			bbar: new Ext.PagingToolbar( {
	            pageSize : purOrSaleOrderPageSize,
	        	store : show_details_store,
	       	 	displayInfo : true,
	        	displayMsg : '第 {0} - {1} 条  共 {2} 条',
	        	emptyMsg : "没有记录"
	        	
	        } )
		} );
		
		var view_panel = new Ext.FormPanel( {
	//	      title:'浏览订单',
//	          applyTo : document.body,
		      items:[
		      	{
		          height:60,
		          layout:'hbox',
		          border:false,
		          layoutConfig: 
		             {     
		               padding:'5',
					   align:'middle' 
                  },
		          items : [
					 {				    
						xtype : 'label',
					    text : '浏览采购订单明细',
					    style : 'color:#000;font-size:26px;background:#fff'
					 }, {
		                xtype:'spacer',
                        flex:0.5
		             }, {
		             	xtype : 'button',
		             	text : '切换到单头浏览方式',
		             	margins:'0',
		             	handler : showPurByMode
		             }, {
	                     xtype : 'textfield',
	                     name : '_codeOfBuyer'
	                 }, {
		                  xtype : 'button',
		                  text : '查找单据号',                   
		                  margins : '0 10',
		                  handler : searchByCode
		             }, {
		                  xtype : 'button',
		                  text : '高级查找', 
		                  handler : queryByComplex
		             }, {
		                  xtype : 'spacer',
		                  flex : 1
		             }, {
		                  xtype : 'button',
		                  text : '新增采购订单',
		                  margins:'0 50',
		                  handler : toAddPurchase
		             }
		         ]
		      }, 
		      	show_details_grid
		    ]
		} );
		
	//	if(!value || (value && value.trim()=='') ) {
	//        Ext.MessageBox.alert("提示","请输入单据号");
	//  } else {
	        		      
	//  }
		
		// 区县下拉框
		var dist_cmb = getDistrictCombox(RES_PATH);// dist_cmb.setWidth(80);
		dist_cmb.hiddenName = null;
		dist_cmb.name = 'district';
		// 城市下拉框
		var city_cmb = getCityCombox(RES_PATH, dist_cmb);
		city_cmb.hiddenName = null;
		city_cmb.name = 'city';
		// 省份下拉框
		var prov_cmb = getProvinceCombox(RES_PATH, city_cmb, dist_cmb);
		prov_cmb.hiddenName = null;
		prov_cmb.name = 'province';
			
		var purchase_areaId_hidden = new Ext.form.Hidden( {
			name : 'areaId'
		});
	
//		function createAddExecBtn(value, metadata, record, 
//			rowIndex, colIndex, store) {
//	
//			return '<div><a id="' + PUR_UPDATE_STRING + record.id + view_panel.main_win.versionCode + '" href="#">打开</a></div>';
//		}
		
		
//		var ds_pur_status_select = new Ext.data.JsonStore({
//           url:Uec3.App.Constants.homeUrl+"/dictionary/findByVarGroup.do?group=order_status",
//           root: "",
//           autoLoad:true,
//           fields:[{name:'varIndex',type:'int'},{name:'varName',type:'string'}]
//        }); 
		
		var ds_pur_status_select = getDictionaryStore(RES_PATH, {
			group : 'order_status'
		});
		
		var status_cmb = getDictionaryComboBox(ds_pur_status_select, 'remote', 'status',
				'单据状态', 'status', 200);
		
		var advanced_search_form_panel = new Ext.form.FormPanel({
		         labelSeparator : "：",
		         frame:true,
		         border:false,			    
		         items:[
		            {
		              xtype:'textfield',
				      width : 200,
		              fieldLabel:'单据号',
		              name:'codeOfBuyer'
		            }, status_cmb, {
		               xtype:'textfield',
				       width : 200,
		               fieldLabel:'供货商',
		               name:'partnerNameByBuyer' 
		            },{
		               xtype:'datefield',
				       width : 200,
		               fieldLabel:'开始时间',
		               name:'gmtStart' ,
		               format:'Y-m-d'
		            },{
		               xtype:'datefield',
		               width : 200,
		               fieldLabel:'结束时间',
		               name:'gmtEnd',
		               format:'Y-m-d'
		            },{
		               xtype:'panel',
		               layout:'hbox',
		               border: false,
		               ctCls:'x-form-item',
		               items:[
		                 {
		                   xtype:'label',
		                   text:'进价(金额)：',
		                   margins:'4 0'
		                  // style:'font-size:15px'
		                   //ctCls:'x-form-item-label'
		                 },{
		                   xtype:'textfield',
		                   name:'minAmount',
		                   width:90,
		                   margins:'0 0 0 35'
		                 },{
		                    xtype:'label',
		                    text:'——'
		                 },{
		                    xtype:'textfield',
		                    name:'maxAmount', 
		                    width:90
		                 }
		              ]
		              
		            }
		         ],
		      buttons:[
		        { 
		          text:'查找',
				  handler : searchResultByCondition
		        },{
		     	  text:'关闭',
		     	  handler : function(){	
		     	    openWind.hide();
		     	  }
		        }
		      ]
			
		});
		
		
		
		
//		Ext.util.Observable.capture(show_details_store, function(e){
//			if(e == 'load'){
//				addUpdateDetailEvent();
//			}
//		});
//		
//		function addUpdateDetailEvent() {
//			var records = show_details_store.getRange();
//			Ext.each(records, function(record) {
////	alert(PUR_UPDATE_STRING + record.id + view_panel.main_win.versionCode);
//				var obj = Ext.get(PUR_UPDATE_STRING + record.id + view_panel.main_win.versionCode);
//				obj.on('click', function() {
//					toUpdatePur(this);	
//				}.bind(record));
//				
//			});	
//		}
		
		var openWind = new Ext.Window({
			title:'高级查找',
		    layout:'fit',
	    	width:380,
	    	closeAction:'hide',
	    	height:330,
			resizable :true,
			shadow : true,
			modal :true,
	    	closable:true,
	    	bodyStyle:'padding:5 5 5 5',
	    	animCollapse:true,
			items:[advanced_search_form_panel]
	    });
		
	    function toAddPurchase() {
	    	var desktop = Uec3.App.getDesktop();   
			desktop.launchWindowByParam("addOutPurchaseOrderWindowCreator",{});
//	    	openByUrl(PUR_TO_ADD_NEW_URL, '新增订单');
	    }
	    
	    /**
		 * 根据采购面板得到表单信息并转换成字符串
		 * 
		 * @return {}
		 */
		function getPurFormValues() {
			var form_values = advanced_search_form_panel.getForm().getValues();
	
			for (var j in form_values) {
				form_values[j] = castNoSelToNULL(form_values[j]);
			}
	
			form_values = Ext.util.JSON.encode(form_values);
	
			return form_values;
		}

		
	    function searchResultByCondition() {
	    	var values = getPurFormValues();
			if(values) {
	    		show_details_store.baseParams = {conditions : values};
			} else {
				show_details_store.baseParams = {};
			}
			show_details_store.load();
	    	openWind.hide();
	    }
	    
	    function queryByComplex() {
	    	advanced_search_form_panel.getForm().reset();
	    	status_cmb.clearValue();
			openWind.show();
	    }
		
		function searchByCode() {
//			var value = view_panel.findById('_codeOfBuyer').getValue();
			var value = view_panel.getForm().findField('_codeOfBuyer').getValue();
			
	//		alert(value);
			show_details_store.baseParams = {codeOfBuyer : value};
			
			loadDetailStore();
			
		}
		
		function showPurByMode() {
			var desktop = Uec3.App.getDesktop();   
			desktop.launchWindowByParam("showPurchaseOrderWindowCreator",{});
//			openByUrl(SHOW_PUR_MODE_URL, '单头浏览');
		}
		
	//	function getPurNumber() {
	//		Ext.Ajax.request( {
	//			url : PUR_INITIAL_BUTNS_URL,
	//			params : {status : init_status},
	//			success : function(data) {
	//						
	//			}
	//		} );
	//	}
		
		function loadDetailStore() {
	//		var obj = {
	//			callback : function(r) {
	//				if(r.length == 0) {
	//					
	//				}
	//				show_details_store.allNum = 0;
	//				show_details_store.seqNum = 0;
	//			}
	//		};
					
			show_details_store.load();
		}
		
		loadDetailStore();
		
		return view_panel;
	}
});




